package com.wonders.frame.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gcr.server.response.Response;
import com.google.gson.JsonObject;
import com.wonders.frame.common.Enum.ResponseCodeEnum;
import com.wonders.frame.common.Enum.SessionKeyEnum;
import com.wonders.frame.common.QueryForm;
import com.wonders.frame.controller.core.CoreController;
import com.wonders.frame.entity.AuthAccount;
import com.wonders.frame.entity.AuthRole;
import com.wonders.frame.entity.AuthRolePermission;
import com.wonders.frame.entity.form.AuthRoleForm;
import com.wonders.frame.entity.form.AuthRolePermissionForm;
import com.wonders.frame.service.AuthRoleService;
import com.wonders.frame.service.Core.CoreCurdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;


@RestController
@RequestMapping("/authRole")
public class AuthRoleController extends CoreController<AuthRole> {
    Logger log = LoggerFactory.getLogger(AuthRoleController.class);
    @Autowired
    private AuthRoleService service;
    @Override
    protected CoreCurdService getService() {
        return service;
    }

    private final ReentrantLock lock=new ReentrantLock();

    @RequestMapping("save")
    public Response save(@RequestBody AuthRoleForm roleForm){
        try {
            lock.lock();
            log.info("request:authRole/save");
            log.info(roleForm.toString());
            //唯一性判断
            if(service.checkUniqueRoleCode(roleForm.getId(),roleForm.getRoleCode())){
                AuthRole authRole=service.save(roleForm);
                return successResponse(authRole);
            }else {
                return getResponse(null, ResponseCodeEnum.ROLECODE_REPEAT.getCode(),ResponseCodeEnum.ROLECODE_REPEAT.getMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }finally {
            lock.unlock();
        }
    }



    @GetMapping("/getCheckedPermission")
    public Response getCheckedPermission(String roleId){
        try {
            log.info("request:authRole/getCheckedPermission");
            log.info("roleId="+roleId);
            List<AuthRolePermission> list=service.getCheckedPermission(roleId);
            String [] checkedPermissionId=new String[list.size()];
            for (int i=0;i<list.size();i++) {
                checkedPermissionId[i]=list.get(i).getPermissionId();
            }
            return successResponse(checkedPermissionId);
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    @PostMapping("/updateRolePermission")
    public Response updateRolePermission(@RequestBody AuthRolePermissionForm authRolePermissionForm){
        try {
            log.info("request:authRole/updateRolePermission");
            log.info(authRolePermissionForm.toString());
            service.updateRolePermission(authRolePermissionForm.getRoleId(),authRolePermissionForm.getCheckedKeys());
            return successResponse(null);
        }catch (Exception e){
            e.printStackTrace();
            return  errorResponse();
        }
    }

    @GetMapping("/getRole")
    public Response getRole(HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            AuthAccount acc = (AuthAccount)session.getAttribute(SessionKeyEnum.USERINFO.name());
            return successResponse(service.getRole(new ArrayList<>(acc.getRoles())));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //根据用户Id查找该用户下绑定的全部角色
    @RequestMapping("/getRolesByAccountId")
    public Response getRolesByAccountId(@RequestBody QueryForm form, HttpServletRequest request){
        try {
            return successResponse(service.getRolesByAccountId(form,request));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //根据角色RoleId查询所有拥有该角色的用户(角色赋权-页面显示)
    @RequestMapping("/getUsersByRoleId")
    public Response getUsersByRoleId(@RequestBody QueryForm form){
        try {
            return successResponse(service.getUsersByRoleId(form));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }
    //根据角色RoleId查询无该角色的用户（角色赋权-新增）
    @RequestMapping("/getUsersWithoutRole")
    public Response getUsersWithoutRole(@RequestBody QueryForm form,HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            AuthAccount acc = (AuthAccount)session.getAttribute(SessionKeyEnum.USERINFO.name());
            return successResponse(service.getUsersWithoutRole(form,acc.getDeptId()));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }
}
